package cn.phecda.boot.common.lang.util;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 用时计时器
 *  
 * @author wanpinwei
 */
public class CostTimer {
    private long start = System.nanoTime();

    public void plusTime(long nanoTime) {
        if (nanoTime < 0) {
            nanoTime = nanoTime * -1;
        }
        start -= nanoTime;
    }

    public Duration duration() {
        return Duration.ofMillis(TimeUnit.NANOSECONDS.toMillis(
                System.nanoTime() - start));
    }

    public static Duration duration(Runnable test) {
        CostTimer costTimer = new CostTimer();
        test.run();
        return costTimer.duration();
    }

    /**
     * 重置
     */
    public void reset() {
        start = System.nanoTime();
    }

    /**
     * 时分秒数组
     * @return
     */
    public long[] hms() {
        long seconds = duration().getSeconds();

        long hours = seconds / 3600;
        long minutes = (seconds % 3600) / 60;
        long remaining = (seconds % 3600) % 60;

        return new long[]{hours, minutes, remaining};
    }

    /**
     * 转换成格式(时分秒)
     * @return
     */
    public String toCnTimeString() {
        long[] hms = hms();

        String template = "";
        List<Object> templateParams = new ArrayList<>();
        if (hms[0] > 0) {
            template += "%d时";
            templateParams.add(hms[0]);
        }
        if (hms[1] > 0) {
            template += "%d分";
            templateParams.add(hms[1]);
        }
        if (hms[2] > 0) {
            template += "%d秒";
            templateParams.add(hms[2]);
        }

        return String.format(template, templateParams.toArray());
    }

    /**
     * 格式 00:00:00
     * @return
     */
    public String toTimeString() {
        long[] hms = hms();
        return String.format("%02d:%02d:%02d", hms[0], hms[1], hms[2]);
    }
}
